package cn.zhxu.toys.concurrent;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 基于 Redis 的布隆过滤器
 * @author Administrator
 *
 */
public class RedisBloomFilter extends AbstractBloomFilter {

	private JedisPool jedisPool;

	private String keyPrefix;
	
	/**
	 * @param expectedInsertions 期望插入的个数
	 * @param fpp 期望的误判率 （0， 1）
	 */
	public RedisBloomFilter(int expectedInsertions, double fpp) {
		this(null, expectedInsertions, fpp);
	}
	
	public RedisBloomFilter(JedisPool jedisPool, int expectedInsertions, double fpp) {
		this(jedisPool, null, expectedInsertions, fpp);
	}
	
	public RedisBloomFilter(JedisPool jedisPool, Hasher hasher, int expectedInsertions, double fpp) {
		super(hasher, expectedInsertions, fpp);
		this.jedisPool = jedisPool;
	}
	
	@Override
	public void updateBitArray(String key, long[] positions) {
		try (Jedis jedis = jedisPool.getResource()) {
			String key0 = key(key);
			for (long pos : positions) {
				jedis.setbit(key0, pos, true);
			}
		}
	}

	@Override
	public boolean checkBitArray(String key, long[] positions) {
		try (Jedis jedis = jedisPool.getResource()) {
			String key0 = key(key);
			for (long pos : positions) {
				if (!jedis.getbit(key0, pos)) {
					return false;
				}
			}
			return true;
		}
	}
	
	private String key(String key) {
		return keyPrefix + ":" + key;
	}
	
	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public String getKeyPrefix() {
		return keyPrefix;
	}

	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
}
